import React from 'react';
import { Input, Form, InputNumber, Tooltip, Icon, ConfigProvider } from 'antd';
import { get as getPath } from 'object-path';
import { TreeSelectForm, SearchInput } from '@/components/UserForm';
import request from '@/utils/request';
import AddTable from './AddTable';

const { TextArea } = Input;

/**
 * 编辑时 默认去部门详情接口返回的数据 一级部门的部门列表为空
 * 非树节点操作新增时 部门默认不选择
 * 新增时 默认值为当前部门id
 * 新增时 如果为公司 上级部门为空
 */
const getParentId = ({ isTreeHandle, isEditDepartment, formData, treeNode: { cdType, id } }) => {
    let result = null;
    const getId = cdType === 0 ? null : id;
    const parentId = formData.parentId === 0 ? null : formData.parentId;
    if (isEditDepartment) {
        result = parentId;
    } else if (isTreeHandle) {
        result = getId;
    } else {
        result = null;
    }
    return result;
};
const getDepartmentManagerId = DepartmentManagerId => {
    if (DepartmentManagerId === -1 || DepartmentManagerId === null) {
        return undefined;
    }
    return DepartmentManagerId;
};

/**
 * 新增、编辑部门
 */
const AddPost = props => {
    const {
        form,
        form: { getFieldDecorator },
        /**
         * treeNode 节点上属性
         * id:
         * name:
         * code:
         * parentId:
         * manager:
         * employeeCount:
         * cdType:
         * companyId:
         * children:
         */
        treeNode = {},
        // 是否在树状图进行部门操作
        isTreeHandle = false,
        // 公司id 切换公司做表单项联动操作时需要
        observableId = null,
        isEditDepartment = false,
        formData = {},
        setDepartmentManager,
        setObservableId,
        code
    } = props;
    const companyChange = v => {
        setObservableId(v);
        form.setFieldsValue({
            // 公司更改时要清除
            introduce: null,
            parentId: null,
            departmentManagerId: undefined
        });
    };
    const postMap = () => {
        if (formData.posts && formData.posts.length > 0) {
            return formData.posts.map(item => ({
                key: `id-${item.id}`,
                value: item.id,
                level1: item.firstPositionCode,
                level2: item.secondPositionCode,
                isRelationToEmployee: item.isRelationToEmployee // false为可以删除
            }));
        }
        return [{}];
    };
    const departmentChange = () => {
        form.setFieldsValue({
            departmentManagerId: undefined
        });
    };
    /** 部门主管选中的回调 */
    const handleSelect = (e, o) => {
        setDepartmentManager(getPath(o, 'props.children', ''));
    };
    const limitDecimals = (values = 1) => {
        if (values) {
            return parseInt(values, 10);
        }
        return '';
    };

    const isDuplicate = list => {
        let result = false;
        if (list.length > 1) {
            const valueList = [...list].reduce((prev, curr) => {
                prev.push(curr.value);
                return prev;
            }, []);
            if (valueList.length !== new Set(valueList).size) {
                result = true;
            }
        }
        return result;
    };

    const getParentDom = (el, parentSelector = 'body') => {
        let p = el.parentNode;
        while (p !== document.querySelector(parentSelector)) {
            p = p.parentNode;
        }
        return p;
    };

    return (
        <React.Fragment>
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <Form.Item label="部门名称">
                    {getFieldDecorator('departmentName', {
                        initialValue: isEditDepartment ? getPath(formData, 'departmentName', '') : '',
                        rules: [
                            {
                                required: true,
                                message: '请输入部门名称'
                            },
                            {
                                min: 2,
                                max: 50,
                                message: '请输入2~50个字符'
                            },
                            {
                                pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                message: '此处不能输入空格'
                            }
                        ]
                    })(<Input placeholder="请输入部门名称" />)}
                </Form.Item>
                <Form.Item label="所属公司">
                    {getFieldDecorator('companyId', {
                        /**
                         * 编辑时禁用公司
                         */
                        initialValue: treeNode.companyId || formData.companyId,
                        rules: [
                            {
                                required: true,
                                message: '请选择公司'
                            }
                        ]
                    })(
                        <TreeSelectForm
                            params={{ permissionUrl: code }}
                            requireParam={['permissionUrl']}
                            getData={params =>
                                request('/api/org/v1/functional/list', {
                                    params
                                }).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            onChange={companyChange}
                            fieldsName={{
                                value: 'id',
                                title: 'companyName'
                            }}
                            Props={{
                                placeholder: '请选择公司',
                                showArrow: true,
                                disabled: formData.parentId === 0
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="上级部门">
                    {getFieldDecorator('parentId', {
                        initialValue: getParentId({
                            isEditDepartment,
                            isTreeHandle,
                            formData,
                            treeNode
                        })
                    })(
                        <TreeSelectForm
                            params={{
                                companyId: observableId,
                                permissionUrl: code
                            }}
                            requireParam={['permissionUrl']}
                            getData={params =>
                                request('/api/org/v1/functional/list', {
                                    params
                                }).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            onChange={departmentChange}
                            fieldsName={{
                                value: 'id',
                                title: 'departmentName'
                            }}
                            Props={{
                                placeholder: '请选择部门',
                                showArrow: true
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="部门主管">
                    {getFieldDecorator('departmentManagerId', {
                        initialValue: isEditDepartment
                            ? getDepartmentManagerId(formData.departmentManagerId)
                            : undefined
                    })(
                        <SearchInput
                            params={{
                                companyId: observableId
                            }}
                            requireParam={['companyId']}
                            getData={params =>
                                request('/api/oa/v1/department/getdepartmentmanager', {
                                    method: 'POST',
                                    data: params
                                }).then(res => {
                                    if (res && res.code === 10000) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            selectProps={{
                                placeholder: '请选择部门主管',
                                allowClear: true
                            }}
                            fieldsName={{
                                value: 'departmentManagerId',
                                title: 'departmentManager',
                                extraParams: 'departmentManager'
                            }}
                            onChange={handleSelect}
                        />
                    )}
                </Form.Item>
            </ConfigProvider>

            <ConfigProvider getPopupContainer={trigger => getParentDom(trigger, '.postContainer')}>
                <Form.Item
                    label={
                        <span>
                            关联职位&nbsp;
                            <Tooltip title="定义该部门下允许招聘和入职的职位列表。" overlayStyle={{ width: '160px' }}>
                                <Icon type="question-circle-o" />
                            </Tooltip>
                        </span>
                    }
                >
                    {getFieldDecorator('postIds', {
                        initialValue: isEditDepartment ? postMap() : [{}],
                        rules: [
                            {
                                required: true,
                                validator(_, value, callback) {
                                    if (!value[0].value) {
                                        callback('请选择关联职位！');
                                    } else if (isDuplicate(value)) {
                                        callback('职位重复，请重新选择!');
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ]
                    })(<AddTable />)}
                </Form.Item>
            </ConfigProvider>
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <Form.Item label="部门介绍" help="5--400个字符">
                    {getFieldDecorator('introduce', {
                        initialValue: isEditDepartment ? formData.introduce : '',
                        rules: [
                            {
                                min: 5,
                                max: 400,
                                message: '只能输入5--400个字符'
                            }
                        ]
                    })(<TextArea placeholder="请输入至少五个字符" rows={4} />)}
                </Form.Item>
                <Form.Item label="部门编制">
                    {getFieldDecorator('planNum', {
                        initialValue: isEditDepartment ? formData.planNum || '' : '',
                        rules: [
                            {
                                required: true,
                                message: '请输入部门编制人数，必须为正整数'
                            }
                        ]
                    })(
                        <InputNumber
                            placeholder="请填写部门编制人数"
                            style={{ width: '100%' }}
                            step={1}
                            min={1}
                            max={999999999}
                            formatter={limitDecimals}
                            parser={limitDecimals}
                        />
                    )}
                </Form.Item>
            </ConfigProvider>
        </React.Fragment>
    );
};
export default AddPost;
